package com.aggron.concurrency.commonunsafe;

import com.aggron.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;


import java.util.HashSet;
import java.util.Set;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author LR2SD
 * @description
 * @date 2018-06-11 19:39
 */
@Slf4j
@NotThreadSafe
public class HashSetExample1 {
    /*
     * 请求总数
     */
    public static  int clientTotal=5000;
    /**
     * 同时执行线程的总数
     */
    public static  int threadTotal =200;


    private static Set<Integer> set=new HashSet<>();
    public static void main(String [] args) throws Exception {
        //线程池
        ExecutorService executorService= Executors.newCachedThreadPool();
        //信号量--允许的最大并发量
        final Semaphore semaphore=new Semaphore(threadTotal);

        //阻塞当前线程，直至线程减少到0时
        final CountDownLatch countDownLatch=new CountDownLatch(clientTotal);

        for (int i = 0; i < clientTotal; i++) {
            final int count=i;
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    add(count);
                    semaphore.release();
                } catch (Exception e) {
                    log.error(e.getMessage(),e);
                }
                countDownLatch.countDown();

            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("size {}",set.size());
    }

    private static void add(int i){set.add(i);

    }
}
